<template>
    <div>
        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
            :mode="mode" />
        <Editor style=" overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig"
            :mode="mode" @onCreated="handleCreated" />
    </div>
</template>
<script>// @ts-nocheck

import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { onBeforeUnmount, ref, shallowRef, onMounted, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

export default {
    components: { Editor, Toolbar },
    setup(props,{ emit }) {
        // 编辑器实例，必须用 shallowRef
        const editorRef = shallowRef()

        // 内容 HTML
        const valueHtml = ref('<p>hello</p>')

        // 挂载钩子
        onMounted(() => {
            
        })
        // 配置功能组
        const toolbarConfig = {
            // 过滤掉不需要的功能
            excludeKeys: [
                'todo',
                'group-video',
                'fullScreen'
            ]
        }
        const editorConfig = {
            placeholder: '请输入内容...',
            MENU_CONF: {
                uploadImage: {
                    server: "http://43.138.224.168:3000/admin/upload",
                    headers: {
                        Authorization: sessionStorage.getItem('token')
                    },
                    customInsert(res, insertFn) {
                        console.log(res)
                        // 从 res 中找到 url alt href ，然后插入图片
                        insertFn(res.url, res.url, res.url)
                    }
                }
            }
        }

        // 组件销毁时，也及时销毁编辑器
        onBeforeUnmount(() => {
            const editor = editorRef.value
            if (editor == null) return
            editor.destroy()
        })

        const handleCreated = (editor) => {
            editorRef.value = editor // 记录 editor 实例，重要！
        }
        // 监听富文本框的值改动 改动后传递给父组件
        watch(valueHtml, (newValue, oldValue) => {
            emit("GetArticleContext", newValue)
        })

        return {
            editorRef,
            valueHtml,
            mode: 'default', // 或 'simple'
            toolbarConfig,
            editorConfig,
            handleCreated
        }
    },
}
</script>    